package com.huibei.wateradmin.authority.controller;

import com.huibei.wateradmin.authority.domain.User;
import com.huibei.wateradmin.authority.message.ClientMenuInfo;
import com.huibei.wateradmin.authority.message.ReqRegisterMsg;
import com.huibei.wateradmin.authority.service.MenuService;
import com.huibei.wateradmin.authority.service.UserService;
import com.huibei.wateradmin.authority.util.Err;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by wanglinlin on 2016/7/16.
 */
@RestController
@RequestMapping(value = "/admin/account")
public class AccountController {
    @Autowired
    private UserService userService;
    @Autowired
    private MenuService menuService;

    @RequestMapping(value = "/toLogin",method = RequestMethod.GET)
    public ModelAndView toLogin() {
        ModelAndView mv = new ModelAndView("account/login");
        return mv;
    }

    @RequestMapping(value = "/login")
    public String login(HttpServletRequest request , String email , String password) {
        System.out.println(email+"...."+password);
        //用户信息
        User user = userService.checkLogin(email, password);
        request.getSession().setAttribute("userInfo", user);


        if (user != null) {
            //菜单信息
            List<ClientMenuInfo> menuList = menuService.getUserMenus(user.getUserId());
            System.out.println(">>>>>菜单数量>>>>"+menuList.size());
            request.getSession().setAttribute("menus",menuList);
            return "success";
        } else {
            return Err.error_username_or_password.getContent();
        }
    }

    @RequestMapping(value = "/registerPage",method = RequestMethod.GET)
    public ModelAndView registerPage() {
        ModelAndView mv = new ModelAndView("account/register");
        return mv;
    }

    @RequestMapping(value = "/register",method = RequestMethod.POST)
    @ResponseStatus(HttpStatus.OK)
    public void register(@Valid @ModelAttribute ReqRegisterMsg msg) {
        userService.create(msg.getEmail(),msg.getPassword(),msg.getCnName());
    }

    @RequestMapping(value = "/main",method = RequestMethod.GET)
    public ModelAndView main() {
        ModelAndView mv = new ModelAndView("layout/main");
        return mv;
    }

    @RequestMapping(value = "/offline")
    public ModelAndView offline(HttpServletRequest request) {
        request.getSession().removeAttribute("userInfo");
        request.getSession().invalidate();
        ModelAndView mv = new ModelAndView("redirect:");
        return mv;
    }

}
